#include "Vehicle.h"
#include "Transform.h"
#include "../Time.h"
#include "../GameObject.h"

mtBEGIN(Vehicle)
	mtBASE(ECS::Component);
	mtMETHOD(onStart);
	mtMETHOD(onUpdate);
mtEND

Vehicle::Vehicle() :
	_cachedTransform(nullptr),
	velocity(0.2f)
{

}

void Vehicle::onStart()
{
	_cachedTransform = getComponent<Transform>();
	GameObject* go = (GameObject*)getAssembly();
	connect(go->eventUpdate, this, &Vehicle::onUpdate);
}

void Vehicle::onUpdate()
{
	if (!_path.empty())
		doMoveByPath();
}

void Vehicle::setPath( int length, IntPoint* path )
{
	_path.resize(length);
	for (int i = 0; i < length; ++i)
	{
		_path[i] = Vector2((float)path[i].x, (float)path[i].y);
	}
}

void Vehicle::doMoveByPath()
{
	Vector2 position = _cachedTransform->getPosition();
	float path = velocity * Time::deltaTime;

	size_t pointIndex = 0;
	Vector2& next = _path.at(pointIndex);
	float distance = (next - position).length();

	while (path > distance && pointIndex < _path.size())
	{
		path -= distance;
		position = next;
		pointIndex = 0;
		pointIndex++;
		if (pointIndex < _path.size())
		{
			next = _path[pointIndex];
			distance = (next - position).length();
		}
	}
	auto direction = (next - position).normalized();
	position = position + direction * path;
	if (pointIndex > 0)
		_path.erase(_path.begin(), _path.begin() + pointIndex);

	_cachedTransform->setPosition(position);
	_cachedTransform->setRotation(direction);
}
